package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩对后台控制命令应答
 * 充电桩对后台服务器的后台控制命令报文应答
 */
@Data
public class Cmd6 extends ProtocolDataBase {

    public static final int MIN_SIZE = 43;

    private int v1;
    private int v2;
    private String sn;                        // 充电桩编码
    private int pilePort;                     // 充电枪口: 只有一机一桩此参数可为 0，多枪编号从 1 开始
    private int paramSign;                    // 命令启始标志
    private int paramNum;                     // 命令个数
    private int code;                         // 命令执行结果

    public Cmd6(){
        super.setCmd(6);
    }

    public static Cmd6 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd6 cmd = new Cmd6();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节充电枪口
        cmd.pilePort = getUint8(dataField[offset++]);
        // 4字节命令启始标志
        cmd.paramSign = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 1字节命令个数
        cmd.paramNum = getUint8(dataField[offset++]);
        // 1字节命令执行结果
        cmd.code = getUint8(dataField[offset++]);
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd6#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("类型 [0-查询/ /1-设置]:").append(pilePort).append("\n");
        buffer.append("命令启始标志:").append(paramSign).append("\n");
        buffer.append("命令个数:").append(paramNum).append("\n");
        buffer.append("命令执行结果:").append(code).append("\n");
        return buffer.toString();
    }
}
